#!/usr/bin/python
# -*- coding: UTF-8 -*-

import MySQLdb
import re
import os
import sys
import time

# 打开数据库连接
db = MySQLdb.connect("192.168.88.63", "root", "c4xRVCY2uECX1XAqcJyQy", "ioms", charset='utf8' )
# 使用cursor()方法获取操作游标 
cursor = db.cursor()

deploy_ip = "192.168.88.84"

def oms_monitor():
    '''
    OMS进程监控，轮询查看数据库中进程pid，若异常更新pstatus
    '''
    #清空记录文件
    f=open('/tmp/process.txt', "w+")
    f.seek(0)
    f.truncate()

    sql = "select * from process_process_daemon where buildenv='%s';"%(deploy_ip)
    try:
        #清空记录文件
        f=open('/tmp/oms-process.txt', "w+")
        f.seek(0)
        f.truncate()

        # 执行SQL语句
        cursor.execute(sql)
    
        # 获取所有记录列表
        results = cursor.fetchall()
        for row in results:
            pname = row[2]
            pid = os.popen("pgrep -f %s"%(pname))
            ppid = pid.readlines()
            if len(ppid) <= 0:
                ppid = "1"
                pid_error_update_sql = "update process_process_daemon set pstatus = '1', pid = ' ' where alias='%s' and buildenv='%s';"%(pname, deploy_ip) 
                cursor.execute(pid_error_update_sql)
                db.commit()
            else:
                for p in range(len(ppid)):
                    pid_success_update_sql = "update process_process_daemon set pstatus = '0', pid = '%s' where alias='%s' and buildenv='%s';"%(str(ppid[p]).strip(), pname, deploy_ip)
                    cursor.execute(pid_success_update_sql)
                    db.commit()
                    with open('/tmp/process.txt','a+') as f:
                        f.write(pname+","+str(ppid[p]).strip()+"\n")
    except Exception as e:
        print(e)

def oms_start():
    '''
    OMS进程开启,执行start,根据pid是否为空更新数据库,返回状态码
    '''
    pass

def oms_stop():
    '''
    OMS进程关闭,执行stop,根据pid是否为空更新数据库,返回状态码
    '''
    pass

def oms_add():
    '''
    自动添加process.txt和process_jobcenter.txt中的进程到后台监控
    '''
    for line in open("/usr/local/zabbix/scripts/process.txt"): 
        host = line.split(",")[0]
        alias = line.split(",")[1]
        pname = alias.split("/")[-1]

        former_sql = "select id from process_process_daemon where buildenv = '%s' and alias = '%s'" % (host, alias)
        latter_sql = "insert into process_process_daemon(pname, alias, buildenv, port, pstatus, retry_time, user, standard_num) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');" % (pname, alias, host, "32022", "1", "0", "webadmin", "1")
        result = cursor.execute(former_sql)
        if result:
            #已存在记录，则不进行插入
            #print("已存在 %s-%s 记录，不进行插入" % (host, alias))
            pass
        else:
            #不存在记录则插入
            nowtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            print("%s 正在插入 %s-%s " % (nowtime, host, alias))
            cursor.execute(latter_sql)
            db.commit()

    for line in open("process_jobcenter.txt"):
        host = line.split(",")[0]
        alias = line.split(",")[1]
        pname = alias.split("/")[-1]

        former_sql = "select id from process_process_daemon where buildenv = '%s' and alias = '%s'" % (host, alias)
        latter_sql = "insert into process_process_daemon(pname, alias, buildenv, port, pstatus, retry_time, user, standard_num) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');" % (pname, alias, host, "32022", "1", "0", "webadmin", "1")
        result = cursor.execute(former_sql)
        if result:
            #已存在记录，则不进行插入
            #print("已存在 %s-%s 记录，不进行插入" % (host, alias))
            pass
        else:
            #不存在记录则插入
            nowtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            print("%s 正在插入 %s-%s " % (nowtime, host, alias))
            cursor.execute(latter_sql)
            db.commit()

if __name__ == '__main__':
    if sys.argv[1] == "monitor":
        oms_monitor()
    elif sys.argv[1] == "start":
        oms_start()
    elif sys.argv[1] == "stop":
        oms_stop()
    elif sys.argv[1] == "add":
        oms_add()

    db.close()    

